package JUC.comsumer10Producer2;


import java.awt.geom.QuadCurve2D;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @className: SyncConPro
 * @Description:
 * @Author: wangyifei
 * @Date: 2022/9/5 21:14
 */
public class SyncConPro {
    private Queue<Integer> queue = new LinkedList<>();
    public synchronized void producer(Integer i){
        // 如果队列中没有数据，则进入等待
        while( queue.size() >= 15){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        queue.add(i);
        // 尾插结束之后，唤醒其他线程
        notifyAll();
    }
    public synchronized Integer consumer(){
        // 如果 queue 的容量超过了 15 最大容量，则进入等待

        while(queue.isEmpty()){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Integer poll = queue.poll();
        // 通知其他线程，开始干活
        notifyAll();
        return poll ;
    }

    public static void main(String[] args) {
        SyncConPro queue = new SyncConPro();
        ThreadPoolExecutor pool = new ThreadPoolExecutor( 15 , 15 , 10000
                , TimeUnit.SECONDS , new ArrayBlockingQueue<Runnable>(100));
        for(int i = 0 ; i < 5 ; i++){
            pool.execute( () -> {
                for (int j = 0; j <2; j++) {
                    queue.producer(j);
                    System.out.println("producer " + j);
                }
            });
        }

        for (int i = 0; i < 10; i++) {
            pool.execute(() ->{

                System.out.println("consumer " + queue.consumer());
            });
        }

        pool.shutdown();
    }
}
